package com.iqiju.guagua.photo.wx.mini.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.iqiju.guagua.photo.wx.mini.mapper.WxMiniAppConfigMapper;
import com.iqiju.guagua.photo.wx.mini.model.WxMiniAppConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class WxMiniAppConfigService extends ServiceImpl<WxMiniAppConfigMapper, WxMiniAppConfig> {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public String selectByTypeAndKey(Long wxMiniAppId, String type, String key){
        String configKey = getWxConfigKey(wxMiniAppId,type,key);
        String value = stringRedisTemplate.opsForValue().get(configKey);
        if (value!=null&&value.trim().length()>0){
            return value;
        }

        QueryWrapper<WxMiniAppConfig> wrapper = new QueryWrapper<>();
        wrapper.eq("wx_mini_app_id",wxMiniAppId);
        wrapper.eq("type",type);
        wrapper.eq("key_name",key);
        List<WxMiniAppConfig> list = list(wrapper);
        if (list.isEmpty()){
            return null;
        }
        WxMiniAppConfig wxMiniAppConfig = list.get(0);
        stringRedisTemplate.opsForValue().set(configKey,wxMiniAppConfig.getValue(),30, TimeUnit.DAYS);
        return wxMiniAppConfig.getValue();
    }

    private String getWxConfigKey(Long wxMiniAppId, String type, String key){
        return "IQIJU_MINI_CONFIG_"+wxMiniAppId+"_"+type+"_"+key;
    }

}
